package cz.byteworks.sandbox.html5.newsbox.servlet;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;

import cz.byteworks.sandbox.html5.newsbox.exception.ServiceException;
import cz.byteworks.sandbox.html5.newsbox.service.INewsService;

@WebServlet(urlPatterns = "/messageService", loadOnStartup = 1)
public class MessageServiceServlet extends BaseServlet {

    private static final long serialVersionUID = 8076592681111222823L;
    
    @Autowired(required = true)
    private INewsService newsService;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        StringWriter writer = new StringWriter();
        IOUtils.copy(req.getInputStream(), writer, req.getCharacterEncoding());
        String requestString = writer.toString();
        
        try {
            newsService.sendJSONMessage(requestString);
        } catch (ServiceException e) {
            resp.setStatus(500);
            resp.getWriter().print(e.getMessage());
            return;
        }
        resp.getWriter().print("success");
        resp.setStatus(200);
    }
}
